package com.huangpeng.algorithm.concurrentProgram;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author hp
 * @Title synchronized、ReentrantLock锁、原子类解决、volatile原子性
 * @Package
 * @Date 2021/8/18 14:03
 * @Description
 * @Version 1.0
 */
public class VolatileSolveAtomDemo {
    // 原子Integer类型，保证原子性
    //private AtomicInteger atomicInteger = new AtomicInteger();
    volatile int nums = 0;
    Lock lock = new ReentrantLock();
    // 底层通过CAS保证原子性
    /*public synchronized void addPlusPlus(){
        atomicInteger.getAndIncrement();
    }*/
    // 底层通过synchronized保证原子性
    /*public synchronized void addPlusPlus(){
        nums ++;
    }*/
    // 底层通过ReentrantLock保证原子性
    public void addPlusPlus(){
        lock.lock();
        try {
            nums ++;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        VolatileSolveAtomDemo v = new VolatileSolveAtomDemo();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    v.addPlusPlus();
                }
            },String.valueOf(i)).start();
        }
        // 后台默认两个线程：一个是main线程，一个是gc线程
        while (Thread.activeCount() > 2){
            Thread.yield();
        }
        // 因为volatile不保证原子性，所以选择原子类AtomicInteger来解决volatile不保证原子性问题
        // 最终每次程序执行结果都等于20000
        //System.out.println(Thread.currentThread().getName()+ "\tfinal number result = " + v.atomicInteger.get());
        //System.out.println(Thread.currentThread().getName()+ "\tfinal number result = " + v.nums);
        System.out.println(Thread.currentThread().getName()+ "\tfinal number result = " + v.nums);
    }
}
